package com.yzr.common.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicCasDemo {


    // CompareAndSwap 比较并交换 aba问题
    public static void main(String[] args) {
        AtomicStampedReference<Integer> reference = new AtomicStampedReference<Integer>(1, 1);
        new Thread(() -> {
            System.out.println(reference.compareAndSet(reference.getReference(), 2, reference.getStamp(), reference.getStamp() + 1));
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
            }
            System.out.println(reference.compareAndSet(reference.getReference(), 1, reference.getStamp(), reference.getStamp() + 1));

        }).start();

        new Thread(() -> {
            System.out.println(reference.getStamp());
            System.out.println(reference.compareAndSet(1, 2, reference.getStamp(), reference.getStamp() + 1));

        }).start();


    }
}
